<template>
  <div style="margin-top: 5rem;" class="search-container">


    <el-input v-model="searchQuery" style="max-width: 600px" placeholder="请输入查找的自助信息" class="input-with-select">
      <template #append>
        <el-button :icon="Search" @click="handleSearch" />
      </template>

    </el-input>


  </div>
  <!-- 排行榜的表单 -->
  <div class="rank">
    自助排行榜
  </div>

  <div class="main-style">
    <div class="new-button">
      <el-button type="primary" @click="handleOpenAdd">添加新点评</el-button>
    </div>
    <div class="card-style" v-for="item in mock" :key="item.id" @click="handleToDetail(item.id)">
      <div>
        <img class="img" :src="item.coverImageUrl || '../../../public/test.jpg'" />
      </div>
      <div>
        <div class="title"> {{ item.name }} </div>
        <div class="content">简介： {{ item.diningRecommendation }} </div>>
        <!-- 星级 -->
        <el-rate v-model="item.rating" disabled show-score text-color="#ff9900" score-template=" {value}星" />
        <div>
          <span>{{ item.recommendedCount || "没有" }}人支持该点评</span> &nbsp;
          <span>{{ item.dislike || "没有" }}人不认可该点评</span> &nbsp;
          <span>地址：{{ item.area || "NaN" }}</span>
        </div>
      </div>
    </div>
  </div>

  <!-- 点评窗口 -->
  <!-- 
  // "name": "string",
//   "area": "string",
//   "diningRecommendation": "string",
//   "coverImageUrl": "string" -->
  <el-dialog v-model="showFoodDialog" title="添加点评" width="40%">
    <el-form ref="buffetForm" :model="form" label-width="120px">
      <el-form-item label="店名" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="地址" prop="area">
        <el-input v-model="form.area" type="textarea" />
      </el-form-item>
      <el-form-item label="简介" prop="diningRecommendation">
        <el-input v-model="form.diningRecommendation" type="textarea" />
      </el-form-item>
      <!-- 图片上传 -->
      <el-form-item label="图片上传">
        <el-upload class="upload-demo" action="#" :before-upload="handleImageUpload" :limit="1">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </el-form-item>

    </el-form>

  </el-dialog>

  <!-- Pagination -->
  <el-pagination v-if="totalPages > 1" background layout="prev, pager, next" :total="totalRecords" :page-size="pageSize"
    :current-page="currentPage" @current-change="handlePageChange" />
</template>
<script setup lang="ts">
import router from '@/router';
import axios from 'axios';
import { ElForm, ElFormItem, ElInput, ElButton, ElMessage, ElUpload, ElLoading, } from 'element-plus';
import { ref, onMounted } from 'vue';
import { Search } from '@element-plus/icons-vue';

const mock = ref([]);
const searchQuery = ref('');
const pageSize = ref(10); // Default page size
const currentPage = ref(1); // Current page number
const totalPages = ref(1); // Total number of pages
const totalRecords = ref(0); // Total number of records
const showFoodDialog = ref(false); // 打开点评窗口


interface Form {
  name: string;
  area: string;
  diningRecommendation: string;
  coverImageUrl: string;
}

const form = ref<Form>({
  name: '',
  area: '',
  diningRecommendation: '',
  coverImageUrl: '',
});

const buffetForm = ref();

// 上传图片前的验证函数
const handleImageUpload = async (file: File) => {


  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2; // 限制图片大小为2MB

  if (!isImage) {
    ElMessage.error('只允许上传图片文件。');
    return;
  }

  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB。');
    return;
  }

  const formData = new FormData();
  formData.append('file', file);

  try {

    const loadingInstance = ElLoading.service({ text: '图片上传中...' });
    const response = await axios.post(`/file/upload/file`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    loadingInstance.close();

    form.value.coverImageUrl = response.data.path;
    ElMessage.success('图片上传成功。');
  } catch (error) {
    ElMessage.error('图片上传失败，请重试。');
    console.error('Error uploading image:', error);
  }
}


// 这里可以进行表单数据的提交逻辑，比如发送到后端接口等
// 调用api
const submitForm = async () => {
  try {
    const response = await axios.post('/api/restaurants', form.value);
    console.log('请求成功', response);
  } catch (error) {
    console.error('请求失败', error);
  }
  fetchRestaurants('', currentPage.value, pageSize.value);
  showFoodDialog.value = false;
};

// 关闭窗口




// Fetch restaurants with the given query, pageNum, and pageSize
const fetchRestaurants = (query = '', pageNum = 1, pageSize = 10) => {

  axios
    .get(`/api/restaurants/search`, {
      params: {
        text: query,
        pageNum: pageNum, // Pass pageNum as required by the backend
        pageSize: pageSize, // Pass pageSize as required by the backend
      },
    })
    .then((res) => {
      if (res.data.code === 200) {
        console.log(res.data.data);

        mock.value = res.data.data.listData;
        mock.value.forEach((item: any) => {  //控制评分小数点后1位
          item.rating = formatRating(item.rating);
        });
        totalPages.value = res.data.data.totalPages;
        totalRecords.value = res.data.data.totalRecords;
        console.log(totalPages.value, totalRecords.value);
      } else {
        ElMessage.error('Failed to fetch data');
      }
    })
    .catch(() => {
      ElMessage.error('Error while fetching data');
    });
};

// Handle search action when the user clicks the search button
const handleSearch = () => {
  currentPage.value = 1; // Reset to the first page on a new search
  fetchRestaurants(searchQuery.value, currentPage.value, pageSize.value);
};

// Handle pagination change
const handlePageChange = (pageNum: number) => {
  currentPage.value = pageNum;
  fetchRestaurants(searchQuery.value, currentPage.value, pageSize.value);
};

// Handle navigation to detail view
const handleToDetail = (id: number) => {
  router.push("/buffet/" + id);
};

// 打开点评窗口
const handleOpenAdd = () => {
  showFoodDialog.value = true;
  // ElMessage('正在开发中...');
};
function formatRating(rating: number): string {
  return rating.toFixed(1);
}

// Fetch initial data when the component is mounted
onMounted(() => {
  fetchRestaurants('', currentPage.value, pageSize.value); // Fetch initial data without any search query
});
</script>

<style scoped>
.search-container {
  margin: 1vw;
  padding-bottom: 1%;
}

.new-button {}

.main-style {
  margin: 1vw;
}

.card-style {
  height: 20vh;
  width: 70vw;
  margin: .5rem 0;
  padding: .5rem;
  border-radius: .5rem;
  border: 1px solid black;
  display: flex;
  cursor: pointer;
}

.card-style:hover {
  background-color: #FAFAFA;
}


.title {
  color: red;
  font-size: large;
  font-weight: 650;
}

.img {
  width: 12vw;
  height: 18vh;
  object-fit: contain;
  border-radius: .3rem;
  margin: .5rem;
}

.rank {
  position: fixed;
  right: 2%;
  top: 12%;
  border: 1px solid black;
  width: 20vw;
  height: 80vh;
  border-radius: .5rem;
}

.search-input {
  margin-bottom: 1rem;
}

.search-button {
  margin-left: 1rem;
}

.el-pagination {
  text-align: center;
  margin: 2rem 0;
}
</style>
